<?php

namespace App\Http\Controllers\goods;

use App\Common\Components\ApiController;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends ApiController
{
    /**
     * 获取分类列表
     */
    public function getCategories()
    {
        $param = request()->input('param', []);
        $level = isset($param['level']) ? intval($param['level']) : null;
        $parentId = isset($param['parent_id']) ? intval($param['parent_id']) : null;
        $query = Category::where('deleted_at', 0);
        if ($level !== null) {
            $query->where('level', $level);
        }
        
        if ($parentId !== null) {
            $query->where('parent_id', $parentId);
        }
        
        $list = $query->orderBy('display_order', 'asc')
            ->orderBy('id', 'asc')
            ->get();
        
        return response()->json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => ['list' => $list]
        ]);
    }
    
    /**
     * 创建分类
     */
    public function createCategory()
    {
        $param = request()->input('param', []);
        
        $data = [
            'uniacid' => $param['uniacid'] ?? 0,
            'name' => $param['name'] ?? '',
            'thumb' => $param['thumb'] ?? '',
            'parent_id' => isset($param['parent_id']) ? intval($param['parent_id']) : 0,
            'description' => $param['description'] ?? '',
            'display_order' => isset($param['display_order']) ? intval($param['display_order']) : 0,
            'enabled' => isset($param['enabled']) ? intval($param['enabled']) : 1,
            'is_home' => isset($param['is_home']) ? intval($param['is_home']) : 0,
            'adv_img' => $param['adv_img'] ?? '',
            'adv_url' => $param['adv_url'] ?? '',
            'level' => isset($param['level']) ? intval($param['level']) : 1,
            'advimg_pc' => $param['advimg_pc'] ?? '',
            'advurl_pc' => $param['advurl_pc'] ?? '',
            'plugin_id' => $param['plugin_id'] ?? 0,
            'filter_ids' => $param['filter_ids'] ?? null,
            'small_adv_url' => $param['small_adv_url'] ?? null,
            'created_at' => time(),
            'updated_at' => time(),
            'deleted_at' => 0
        ];
        
        if (empty($data['name'])) {
            return response()->json([
                'code' => 201,
                'msg' => '分类名称不能为空',
                'data' => []
            ]);
        }
        
        // 如果是子分类，验证父分类是否存在
        if ($data['parent_id'] > 0) {
            $parent = Category::where('id', $data['parent_id'])
                ->where('deleted_at', 0)
                ->first();
            if (!$parent) {
                return response()->json([
                    'code' => 201,
                    'msg' => '父分类不存在',
                    'data' => []
                ]);
            }
            $data['level'] = 2;
        } else {
            $data['level'] = 1;
        }
        
        $category = Category::create($data);
        
        return response()->json([
            'code' => 200,
            'msg' => '创建成功',
            'data' => ['id' => $category->id]
        ]);
    }
    
    /**
     * 更新分类
     */
    public function updateCategory()
    {
        $param = request()->input('param', []);
        $id = isset($param['id']) ? intval($param['id']) : 0;
        
        if ($id <= 0) {
            return response()->json([
                'code' => 201,
                'msg' => '分类ID不能为空',
                'data' => []
            ]);
        }
        
        $category = Category::where('id', $id)
            ->where('deleted_at', 0)
            ->first();
        
        if (!$category) {
            return response()->json([
                'code' => 201,
                'msg' => '分类不存在',
                'data' => []
            ]);
        }
        
        $updateData = [];
        
        if (isset($param['name'])) {
            $updateData['name'] = $param['name'];
        }
        if (isset($param['thumb'])) {
            $updateData['thumb'] = $param['thumb'];
        }
        if (isset($param['description'])) {
            $updateData['description'] = $param['description'];
        }
        if (isset($param['display_order'])) {
            $updateData['display_order'] = intval($param['display_order']);
        }
        if (isset($param['enabled'])) {
            $updateData['enabled'] = intval($param['enabled']);
        }
        if (isset($param['is_home'])) {
            $updateData['is_home'] = intval($param['is_home']);
        }
        if (isset($param['adv_img'])) {
            $updateData['adv_img'] = $param['adv_img'];
        }
        if (isset($param['adv_url'])) {
            $updateData['adv_url'] = $param['adv_url'];
        }
        if (isset($param['advimg_pc'])) {
            $updateData['advimg_pc'] = $param['advimg_pc'];
        }
        if (isset($param['advurl_pc'])) {
            $updateData['advurl_pc'] = $param['advurl_pc'];
        }
        if (isset($param['filter_ids'])) {
            $updateData['filter_ids'] = $param['filter_ids'];
        }
        if (isset($param['small_adv_url'])) {
            $updateData['small_adv_url'] = $param['small_adv_url'];
        }
        
        $updateData['updated_at'] = time();
        
        $category->update($updateData);
        
        return response()->json([
            'code' => 200,
            'msg' => '更新成功',
            'data' => []
        ]);
    }
    
    /**
     * 删除分类（软删除）
     */
    public function deleteCategory()
    {
        $param = request()->input('param', []);
        $id = isset($param['id']) ? intval($param['id']) : 0;
        
        if ($id <= 0) {
            return response()->json([
                'code' => 201,
                'msg' => '分类ID不能为空',
                'data' => []
            ]);
        }
        
        $category = Category::where('id', $id)
            ->where('deleted_at', 0)
            ->first();
        
        if (!$category) {
            return response()->json([
                'code' => 201,
                'msg' => '分类不存在',
                'data' => []
            ]);
        }
        
        // 检查是否有子分类
        $childrenCount = Category::where('parent_id', $id)
            ->where('deleted_at', 0)
            ->count();
        
        if ($childrenCount > 0) {
            return response()->json([
                'code' => 201,
                'msg' => '该分类下存在子分类，无法删除',
                'data' => []
            ]);
        }
        
        // 软删除
        $category->update([
            'deleted_at' => time(),
            'updated_at' => time()
        ]);
        
        return response()->json([
            'code' => 200,
            'msg' => '删除成功',
            'data' => []
        ]);
    }
    
    /**
     * 获取分类详情
     */
    public function getCategory()
    {
        $param = request()->input('param', []);
        $id = isset($param['id']) ? intval($param['id']) : 0;
        
        if ($id <= 0) {
            return response()->json([
                'code' => 201,
                'msg' => '分类ID不能为空',
                'data' => []
            ]);
        }
        
        $category = Category::where('id', $id)
            ->where('deleted_at', 0)
            ->first();
        
        if (!$category) {
            return response()->json([
                'code' => 201,
                'msg' => '分类不存在',
                'data' => []
            ]);
        }
        
        return response()->json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => $category
        ]);
    }
    
    /**
     * 获取带子分类的分类列表
     */
    public function getCategoriesWithChildren()
    {
        $categories = Category::where('deleted_at', 0)
            ->where('parent_id', 0)
            ->where('level', 1)
            ->orderBy('display_order', 'asc')
            ->orderBy('id', 'asc')
            ->get();
        
        foreach ($categories as $category) {
            $category->children = Category::where('parent_id', $category->id)
                ->where('deleted_at', 0)
                ->orderBy('display_order', 'asc')
                ->orderBy('id', 'asc')
                ->get();
        }
        
        return response()->json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => ['list' => $categories]
        ]);
    }
}

